package com.zilla.android.lib.ui.photo.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.Toast;
import com.zilla.android.zillacore.libzilla.file.PropertiesManager;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ImageManager {

	private final static String FILE_SAVEPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ PropertiesManager.getInstance().get("cache","")+"/photo/";
	private Uri cropUri;
	private File protraitFile;
	private String protraitPath;

	public final static String SDCARD_MNT = "/mnt/sdcard";
	public final static String SDCARD = "/sdcard";
	
	/** 请求相册 */
	public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
	/** 请求相机 */
	public static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
	/** 请求裁剪 */
	public static final int REQUEST_CODE_GETIMAGE_BYCROP = 2;

	
	public Uri getCropUri() {
		return cropUri;
	}
	public void setCropUri(Uri cropUri) {
		this.cropUri = cropUri;
	}
	public File getProtraitFile() {
		return protraitFile;
	}
	public void setProtraitFile(File protraitFile) {
		this.protraitFile = protraitFile;
	}
	public String getProtraitPath() {
		return protraitPath;
	}
	public void setProtraitPath(String protraitPath) {
		this.protraitPath = protraitPath;
	}

	private static ImageManager mManager = null;
	private ImageManager (){}
	public static synchronized ImageManager getInitialize(){
		if(mManager == null)
			mManager = new ImageManager();
		return mManager;
	}
	
	/**
	 * 
	 * <br/>
	 * <br/>TODO 写图片文件 在Android系统中，文件保存在 /data/data/PACKAGE_NAME/files 目录下
	 * <br/>
	 * <br/>@param context
	 * <br/>@param fileName
	 * <br/>@param bitmap
	 * <br/>@throws IOException		
	 * <br/>
	 * <br/>@date 	2013-11-15下午2:12:06
	 * <br/>@author 仲其鑫
	 */
	public void saveImage(Context context, String fileName, Bitmap bitmap) throws IOException {
		saveImage(context, fileName, bitmap, 100);
	}

	/**
	 * 
	 * <br/>
	 * <br/>TODO 写图片文件 在Android系统中，文件保存在 /data/data/PACKAGE_NAME/files 目录下
	 * <br/>
	 * <br/>@param context
	 * <br/>@param fileName
	 * <br/>@param bitmap
	 * <br/>@param quality
	 * <br/>@throws IOException		
	 * <br/>
	 * <br/>@date 	2013-11-15下午2:12:06
	 * <br/>@author 仲其鑫
	 */
	public void saveImage(Context context, String fileName, Bitmap bitmap, int quality) throws IOException {
		if (bitmap == null || fileName == null || context == null)
			return;

		FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, quality, stream);
		byte[] bytes = stream.toByteArray();
		fos.write(bytes);
		fos.close();
	}

	/**
	 * 写图片文件到SD卡
	 * 
	 * @throws java.io.IOException
	 */
	public void saveImageToSD(Context ctx, String filePath, Bitmap bitmap, int quality) throws IOException {
		if (bitmap != null) {
			File file = new File(filePath.substring(0, filePath.lastIndexOf(File.separator)));
			if (!file.exists()) {
				file.mkdirs();
			}
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
			bitmap.compress(CompressFormat.JPEG, quality, bos);
			bos.flush();
			bos.close();
			if (ctx != null) {
				scanPhoto(ctx, filePath);
			}
		}
	}

	/**
	 * 让Gallery上能马上看到该图片
	 */
	private void scanPhoto(Context ctx, String imgFileName) {
		Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		File file = new File(imgFileName);
		Uri contentUri = Uri.fromFile(file);
		mediaScanIntent.setData(contentUri);
		ctx.sendBroadcast(mediaScanIntent);
	}

	/**
	 * 判断当前Url是否标准的content://样式，如果不是，则返回绝对路径
	 * 
	 * @param mUri
	 * @return
	 */
	public static String getAbsolutePathFromNoStandardUri(Uri mUri) {
		String filePath = null;

		String mUriString = mUri.toString();
		mUriString = Uri.decode(mUriString);

		String pre1 = "file://" + SDCARD + File.separator;
		String pre2 = "file://" + SDCARD_MNT + File.separator;

		if (mUriString.startsWith(pre1)) {
			filePath = Environment.getExternalStorageDirectory().getPath() + File.separator + mUriString.substring(pre1.length());
		} else if (mUriString.startsWith(pre2)) {
			filePath = Environment.getExternalStorageDirectory().getPath() + File.separator + mUriString.substring(pre2.length());
		}
		return filePath;
	}

	/**
	 * 通过uri获取文件的绝对路径
	 * 
	 * @param uri
	 * @return
	 */
	public String getAbsoluteImagePath(Activity context, Uri uri) {
		String imagePath = "";
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = context.managedQuery(uri, proj, // Which columns to
														// return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)

		if (cursor != null) {
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			if (cursor.getCount() > 0 && cursor.moveToFirst()) {
				imagePath = cursor.getString(column_index);
			}
		}

		return imagePath;
	}

	/**
	 * 
	 * <br/>
	 * <br/>TODO 
	 * <br/>
	 * <br/>@param context
	 * <br/>@param uri
	 * <br/>@return		
	 * <br/>
	 * <br/>@date 	2013-11-15下午3:29:51
	 * <br/>@author 仲其鑫
	 */
	public String galleryUriToString(Activity context, Uri uri) {
		String theLarge = "";
		Uri thisUri = uri;
		String thePath = getAbsolutePathFromNoStandardUri(thisUri);

		// 如果是标准Uri
		if (TextUtils.isEmpty(thePath)) {
			theLarge = getAbsoluteImagePath(context, thisUri);
		} else {
			theLarge = thePath;
		}

		String attFormat = FileUtils.getFileFormat(theLarge);
		if (!"photo".equals(MediaUtils.getContentType(attFormat))) {
			return null;
		}
		return theLarge;
	}

	// 裁剪头像的绝对路径
	private Uri getUploadTempFile(Activity context, Uri uri) {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			Toast.makeText(context, "无法保存上传的头像，请检查SD卡是否挂载", Toast.LENGTH_SHORT).show();
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String thePath = getAbsolutePathFromNoStandardUri(uri);

		// 如果是标准Uri
		if (TextUtils.isEmpty(thePath)) {
			thePath = getAbsoluteImagePath( context, uri);
		}
		//获取文件扩展名
		String ext = FileUtils.getFileFormat(thePath);
		ext = TextUtils.isEmpty(ext) ? "jpg" : ext;
		// 照片命名
		String cropFileName = PropertiesManager.getInstance().get("cache", "") + "_crop_" + timeStamp + "." + ext;
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);

		cropUri = Uri.fromFile(protraitFile);
		return this.cropUri;
	}

	// 裁剪头像的绝对路径
	public Uri getUploadTempFile(Context context, Bitmap bitmap) {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			Toast.makeText(context, "无法保存上传的头像，请检查SD卡是否挂载", Toast.LENGTH_SHORT).show();
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

		// 照片命名
		String cropFileName = PropertiesManager.getInstance().get("cache", "") + "_crop_" + timeStamp + ".jpg";
		try {
			// 裁剪头像的绝对路径
			protraitPath = FILE_SAVEPATH + cropFileName;
			protraitFile = new File(protraitPath);
			cropUri = Uri.fromFile(protraitFile);
			saveImageToSD(context, protraitPath, bitmap, 100);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return this.cropUri;
	}

	/**
	 * 拍照后裁剪   REQUEST_CODE_GETIMAGE_BYSDCARD
	 * 
	 * @param data
	 *            原始图片
	 * @param height
	 *            裁剪后图片
	 */
	public void startActionCrop(Activity activity, Uri data, int width, int height) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(data, "image/*");
		if (!VersionUtils.hasHoneycomb()) {
			intent.putExtra("return-data", true);
		}
		intent.putExtra("output", getUploadTempFile(activity, data));
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", width);// 裁剪框比例
		intent.putExtra("aspectY", height);
		intent.putExtra("outputX", width);// 输出图片大小
		intent.putExtra("outputY", height);
		intent.putExtra("scale", true);// 去黑边
		intent.putExtra("scaleUpIfNeeded", true);// 去黑边

		activity.startActivityForResult(intent, REQUEST_CODE_GETIMAGE_BYSDCARD);
	}

	/**
	 * 操作选择
	 * 
	 * @param items
	 */
	public void imageChooseItem(final Activity activity, CharSequence[] items) {
		AlertDialog imageDialog = new AlertDialog.Builder(activity).setTitle("上传头像").setIcon(android.R.drawable.btn_star).setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				// 相册选图
				if (item == 0) {
					startImagePick(activity);
				}
				// 手机拍照
				else if (item == 1) {
					startActionCamera(activity);
				}
			}
		}).create();

		imageDialog.show();
	}

	/**
	 * 选择图片裁剪
	 * 
	 * @param activity
	 */
	private void startImagePick(Activity activity) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		activity.startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_CODE_GETIMAGE_BYCROP);
	}

	/**
	 * 相机拍照
	 * 
	 * @param activity
	 */
	private void startActionCamera(Activity activity) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, getCameraTempFile());
		activity.startActivityForResult(intent, REQUEST_CODE_GETIMAGE_BYCAMERA);
	}

	// 拍照保存的绝对路径
	private Uri getCameraTempFile() {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			// UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像，请检查SD卡是否挂载");
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		// 照片命名
		String cropFileName = PropertiesManager.getInstance().get("cache", "") + "_camera_" + timeStamp + ".jpg";
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);
		cropUri = Uri.fromFile(protraitFile);
		return this.cropUri;
	}

	/**
	 * 
	 * <br/>
	 * <br/>TODO 重新定义图片大小
	 * <br/>
	 * <br/>@param bitmap
	 * <br/>@param screenWidth
	 * <br/>@return		
	 * <br/>
	 * <br/>@date 	2013-11-26下午8:21:09
	 * <br/>@author 仲其鑫
	 */
	public Bitmap resizeBitmap(Bitmap bitmap, int screenWidth) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int newWidth = screenWidth;
		int newHeight = screenWidth * height / width; // 根据屏幕的宽度，计算按比较缩放后的高度
		// calculate the scale
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// create a matrix for the manipulation
		Matrix matrix = new Matrix();
		// resize the Bitmap
		matrix.postScale(scaleWidth, scaleHeight);
		// if you want to rotate the Bitmap
		// matrix.postRotate(45);
		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
		// make a Drawable from Bitmap to allow to set the Bitmap
		// to the ImageView, ImageButton or what ever
		return resizedBitmap;
	}
	/**
	 * 
	 * <br/>
	 * <br/>TODO 重新定义图片大小
	 * <br/>
	 * <br/>@param bitmap
	 * <br/>@param screenWidth
	 * <br/>@return		
	 * <br/>
	 * <br/>@date 	2013-11-26下午8:21:09
	 * <br/>@author 仲其鑫
	 */
	public Bitmap resizeDrawable(Drawable drawable, int screenWidth) {
		Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
		if(bitmap == null)
			return null;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int newWidth = screenWidth;
		int newHeight = screenWidth * height / width; // 根据屏幕的宽度，计算按比较缩放后的高度
		// calculate the scale
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// create a matrix for the manipulation
		Matrix matrix = new Matrix();
		// resize the Bitmap
		matrix.postScale(scaleWidth, scaleHeight);
		// if you want to rotate the Bitmap
		// matrix.postRotate(45);
		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
		// make a Drawable from Bitmap to allow to set the Bitmap
		// to the ImageView, ImageButton or what ever
		return resizedBitmap;
	}
}
